package com.copera.cn.kaka;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.copera.cn.kaka.picpopupwindow.SelectPicPopupWindow;
import com.copera.cn.kaka.util.ActionUrls;
import com.copera.cn.kaka.util.AsyncImageLoader;
import com.copera.cn.kaka.util.AsyncImageLoader.ImageCallBack;
import com.copera.cn.kaka.util.HttpUtils;
import com.copera.cn.kaka.util.UploadUtil;
import com.copera.cn.kaka.util.Utility;
import com.copera.cn.kaka.vo.ShopVo;

public class ShopBasicActivity extends BaseActivity {

	private ApplicationCustomer appc;
	private TextView tshopname, taddress, tphone, textView5;
	private RelativeLayout shop_name, back, address, phone, code, suser, pass,
			title, listview, line_id;
	public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
	List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
	private ImageView head;
	// 自定义的弹出框类
	private SelectPicPopupWindow menuWindow;
	private AsyncImageLoader asyncImageLoader = new AsyncImageLoader();
	private SimpleAdapter simpleAdapter;
	private Button loginButton;
	private boolean bool = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.config_basic);
		appc = (ApplicationCustomer) getApplication();
		initViews();
		initEvent();
		loadHeadImage();

		// 强制为竖屏
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	private void initViews() {
		back = (RelativeLayout) findViewById(R.id.back);
		shop_name = (RelativeLayout) findViewById(R.id.shop_name);
		address = (RelativeLayout) findViewById(R.id.address);
		phone = (RelativeLayout) findViewById(R.id.phone);
		code = (RelativeLayout) findViewById(R.id.code);
		suser = (RelativeLayout) findViewById(R.id.suser);
		pass = (RelativeLayout) findViewById(R.id.pass);
		tshopname = (TextView) findViewById(R.id.tshopname);
		taddress = (TextView) findViewById(R.id.taddress);
		tphone = (TextView) findViewById(R.id.tphone);
		title = (RelativeLayout) findViewById(R.id.title);
		head = (ImageView) findViewById(R.id.head);
		textView5 = (TextView) findViewById(R.id.textView5);
		listview = (RelativeLayout) findViewById(R.id.listview);
		loginButton = (Button) findViewById(R.id.loginButton);
		line_id = (RelativeLayout) findViewById(R.id.line_id);
		list =(ListView)findViewById(R.id.user_blist);
	}

	@Override
	protected void onResume() {

		super.onResume();
		ShopVo shop = getAppCustomer().getShop();
		if (shop.getId().equals(shop.getShopId())) {
			bool = true;
		}
		initValues();
		listItems = new ArrayList<Map<String, Object>>();
		simpleAdapter = new SimpleAdapter(this, listItems, R.layout.user_blist,
				new String[] { "textView7", "textView8" }, new int[] {
						R.id.textView7, R.id.textView8 });
		ListView listView = (ListView) findViewById(R.id.user_blist);
		listView.setAdapter(simpleAdapter);
	}

	public void loadHeadImage() {

		new AsyncTask<String, Integer, JSONObject>() {

			@Override
			protected JSONObject doInBackground(String... params) {
				JSONObject jsonObj = null;
				try {
					String jsonStr = HttpUtils.get(params[0], getAppCustomer()
							.getHttpClient());

					if (jsonStr != null) {
						jsonObj = new JSONObject(jsonStr);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
				return jsonObj;
			}

			@Override
			protected void onPostExecute(JSONObject result) {

				if (result != null) {
					try {
						String headImage = result.getString("headImage");

						Bitmap bitmap = asyncImageLoader.loadBitmap(head,
								ActionUrls.HOST + headImage, getAppCustomer()
										.getHttpClient(), new ImageCallBack() {

									@Override
									public void imageLoad(ImageView imageView,
											Bitmap bitmap) {
										imageView.setImageBitmap(bitmap);
									}
								});
						if (bitmap != null) {
							BitmapDrawable bd = new BitmapDrawable(bitmap);
							head.setBackgroundDrawable(bd);

						}

					} catch (Exception e) {
						e.printStackTrace();
						if (e.getMessage() != null) {

						}
					}
				}
			}

		}.execute(ActionUrls.URL_LOADHEADIMAGE + "?shopId="
				+ appc.getShop().getShopId());

	}

	private void initValues() {
		ShopVo shop = appc.getShop();
		tshopname.setText(shop.getShopName());
		taddress.setText(shop.getAddress());
		tphone.setText(shop.getTrackToday());
		tphone.setText(shop.getPhone1());
		if (!shop.getId().equals(shop.getShopId())) {
			suser.setVisibility(View.GONE);
			line_id.setVisibility(View.GONE);
		}
		new AsyncTask<String, Integer, String>() {
			@Override
			protected String doInBackground(String... params) {
				try {
					String json = HttpUtils.get(ActionUrls.URL_SHOPUSER_BLIST
							+ "?id=" + appc.getShop().getShopId(),
							getAppCustomer().getHttpClient());
					JSONObject jo = new JSONObject(json);
					JSONArray jsonArr = jo.getJSONArray("list");
					if (jsonArr != null && jsonArr.length() > 0) {
						Map<String, Object> listItem;
						for (int i = 0; i < jsonArr.length(); i++) {
							listItem = new HashMap<String, Object>();
							JSONObject object = jsonArr.getJSONObject(i);
							listItem.put("textView7",
									object.getString("loginName"));
							listItem.put("textView8",
									object.getString("password"));
							listItems.add(listItem);
						}
					}
					return jo.getString("size");
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
			}

			protected void onPostExecute(String size) {
				textView5.setText(size + "/");
			}
		}.execute("");
	}
    public void user(View view){
    	
    }
    private ListView list;
	private void initEvent() {
		
		title.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if (bool) {
					// 实例化SelectPicPopupWindow
					menuWindow = new SelectPicPopupWindow(
							ShopBasicActivity.this, itemsOnClick);
					// 显示窗口
					menuWindow.showAtLocation(findViewById(R.id.main),
							Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
				} else {
					Toast.makeText(ShopBasicActivity.this, "只有店长才能修改店铺头像",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		
		back.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();

			}
		});
		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent = new Intent();
				intent.setClass(ShopBasicActivity.this, ShopUserActivity.class);
				startActivity(intent);
				
			}
		});
		listview.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				
			}
		});

		shop_name.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (bool) {
					Intent intent = new Intent();
					intent.setClass(ShopBasicActivity.this,
							ShopNameActivity.class);
					startActivity(intent);
				} else {
					Toast.makeText(ShopBasicActivity.this, "只有店长才能修改店铺名称",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		address.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (bool) {
					Intent intent = new Intent();
					intent.setClass(ShopBasicActivity.this,
							ShopAddressActivity.class);
					startActivity(intent);
				} else {
					Toast.makeText(ShopBasicActivity.this, "只有店长才能修改店铺地址",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		phone.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				if (bool) {
					Intent intent = new Intent();
					intent.setClass(ShopBasicActivity.this,
							ShopPhoneActivity.class);
					startActivity(intent);
				} else {
					Toast.makeText(ShopBasicActivity.this, "只有店长才能修改店长手机",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
		code.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(ShopBasicActivity.this, ShopCodeActivity.class);
				startActivity(intent);
			}
		});
		suser.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(ShopBasicActivity.this, ShopUserActivity.class);
				startActivity(intent);
			}
		});
		pass.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(ShopBasicActivity.this, ShopPassActivity.class);
				startActivity(intent);
			}
		});
		loginButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// 创建退出对话框
				AlertDialog isExit = new AlertDialog.Builder(
						ShopBasicActivity.this).create();
				// 设置对话框标题
				isExit.setTitle("系统提示");
				// 设置对话框消息
				isExit.setMessage("确定要退出吗");
				// 添加选择按钮并注册监听
				isExit.setButton2("取消", listener);
				isExit.setButton("确定", listener);

				// 显示对话框
				isExit.show();
			}
		});
	}

	/** 监听对话框里面的button点击事件 */
	DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			switch (which) {
			case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
				Intent intent = new Intent(ShopBasicActivity.this,
						LoginActivity.class);
				startActivity(intent);
				finish();
				break;
			case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
				break;
			default:
				break;
			}
		}
	};
	// 为弹出窗口实现监听类
	private OnClickListener itemsOnClick = new OnClickListener() {

		public void onClick(View v) {
			menuWindow.dismiss();

			int id = v.getId();
			if (id == R.id.btn_take_photo) {

				String status = Environment.getExternalStorageState();
				if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡
					doTakePhoto();// 用户点击了从照相机获取
				}
			} else if (id == R.id.btn_pick_photo) {

				doCropPhoto();// 从相册中去获取
			} else {
				// finish();
			}

		}
	};

	/**
	 * 拍照获取图片
	 * 
	 */
	protected void doTakePhoto() {
		try {
			File uploadFileDir = new File(
					Environment.getExternalStorageDirectory(), "/upload");
			Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			if (!uploadFileDir.exists()) {
				uploadFileDir.mkdirs();
			}
			picFile = new File(uploadFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
			startActivityForResult(cameraIntent,
					activity_result_camara_with_data);
		} catch (ActivityNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	protected void doCropPhoto() {
		try {
			File pictureFileDir = new File(
					Environment.getExternalStorageDirectory(), "/upload");
			if (!pictureFileDir.exists()) {
				pictureFileDir.mkdirs();
			}
			picFile = new File(pictureFileDir, "upload.jpeg");
			if (!picFile.exists()) {
				picFile.createNewFile();
			}
			photoUri = Uri.fromFile(picFile);
			final Intent intent = getCropImageIntent();
			startActivityForResult(intent, activity_result_cropimage_with_data);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * Constructs an intent for image cropping. 调用图片剪辑程序
	 */
	public Intent getCropImageIntent() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
		intent.setType("image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 400);
		intent.putExtra("outputY", 400);
		intent.putExtra("noFaceDetection", true);

		intent.putExtra("scale", true);
		intent.putExtra("scaleUpIfNeeded", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(picFile));
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		return intent;
	}

	private void cropImageUriByTakePhoto() {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(photoUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("outputX", 400);
		intent.putExtra("outputY", 400);

		intent.putExtra("scale", true);
		intent.putExtra("scaleUpIfNeeded", true);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(picFile));
		intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
		intent.putExtra("noFaceDetection", true); // no face detection
		startActivityForResult(intent, activity_result_cropimage_with_data);
	}

	private File picFile;
	private final int activity_result_camara_with_data = 1006;
	private final int activity_result_cropimage_with_data = 1007;
	private Uri photoUri;

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case activity_result_camara_with_data: // 拍照
			try {
				cropImageUriByTakePhoto();
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		case activity_result_cropimage_with_data:
			try {
				if (photoUri != null && data != null) {
					Bitmap bitmap = decodeUriAsBitmap(photoUri);
					BitmapDrawable bd = new BitmapDrawable(
							Utility.small(bitmap));
					head.setBackgroundDrawable(bd);

					upload(Utility.small(bitmap));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			break;
		}
	}

	private Bitmap decodeUriAsBitmap(Uri uri) {
		Bitmap bitmap = null;
		try {
			bitmap = BitmapFactory.decodeStream(getContentResolver()
					.openInputStream(uri));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return null;
		}
		return bitmap;
	}

	public void upload(Bitmap bitmap) {

		UploadUtil uploadUtil = UploadUtil.getInstance();
		File file = null;

		try {
			file = UploadUtil.saveMyBitmap(bitmap);
		} catch (IOException e) {

			e.printStackTrace();
		}

		Map<String, String> params = new HashMap<String, String>();
		params.put("shopId", getValue("shopId"));
		params.put("type", "headImage");

		uploadUtil.uploadFile(file.getAbsolutePath(), "pic",
				ActionUrls.URL_UPLOAD, params);

	}

}
